package com.yoga.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class AiService {

    @Value("${ai.qwen.api-key}")
    private String apiKey;

    @Value("${ai.qwen.url}")
    private String apiUrl;

    private final OkHttpClient client = new OkHttpClient();
    private final ObjectMapper mapper = new ObjectMapper();

    public String generateRemark(String keywords) {
        try {
            // 使用正确的阿里云百炼平台请求格式
            String json = "{\n" +
                    "  \"model\": \"qwen-turbo\",\n" +
                    "  \"input\": {\n" +
                    "    \"messages\": [\n" +
                    "      {\"role\": \"user\", \"content\": \"请根据以下关键词，生成一段简短的备注，适合用在教室信息管理系统：" + keywords + "\"}\n" +
                    "    ]\n" +
                    "  },\n" +
                    "  \"parameters\": {\n" +
                    "    \"max_tokens\": 200,\n" +
                    "    \"temperature\": 0.7\n" +
                    "  }\n" +
                    "}";

            RequestBody body = RequestBody.create(
                    json, MediaType.parse("application/json"));

            Request request = new Request.Builder()
                    .url(apiUrl)
                    .post(body)
                    .addHeader("Authorization", "Bearer " + apiKey)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("X-DashScope-SSE", "disable")
                    .build();

            Response response = client.newCall(request).execute();//execute是一个同步方法，会阻塞当前线程，直到响应完成

            if (!response.isSuccessful()) {
                return "AI生成失败：HTTP " + response.code();
            }

            String respStr = response.body().string();

            JsonNode root = mapper.readTree(respStr);

            // 解析阿里云百炼平台的响应格式
            JsonNode outputNode = root.path("output");
            if (!outputNode.isMissingNode()) {
                JsonNode textNode = outputNode.path("text");
                if (!textNode.isMissingNode()) {
                    return textNode.asText().trim();
                }
            }

            return "AI生成失败：无法解析响应内容";
        } catch (Exception e) {
            e.printStackTrace();
            return "AI生成失败：" + e.getMessage();
        }
    }
}
